<?php

namespace SunAdmin\Service;

use SunAdmin\Common\Utils;
use SunAdmin\Model\AccountModel;
use SunAdmin\Model\MenusModel;
use think\Exception;

class MenusService
{

    public static function deleteMenus($id)
    {
        $menu = MenusModel::find($id);
        if (empty($menu)) {
            throw new Exception("该菜单不存在或已删除");
        }
        $isChildren = MenusModel::where('pid', $id)->count();
        if($isChildren > 0){
            throw new Exception("本条项目下存在数据,不可以删除");
        }
        MenusModel::where('id', $id)->delete();
        return true;
    }

    public static function edit($menusItemData = []){
        if(!empty($menusItemData['cascader_path'])){
            $menusItemData['pid'] = $menusItemData['cascader_path'][count($menusItemData['cascader_path']) - 1];
        }
        if(empty($menusItemData['type'])){
            throw new Exception("类型/type/字段不能为空");
        }
        if(empty($menusItemData['name'])){
            throw new Exception("名称/name/字段不能为空");
        }
        if($menusItemData['type'] == 'route'){
            if(empty($menusItemData['route_path'])){
                throw new Exception("路由模式下必须填写路由地址");
            }
        }
        if($menusItemData['type'] == 'auth'){
            if(empty($menusItemData['auth_tag'])){
                throw new Exception("权限控制模式下权限标识必填");
            }
        }
        if(!empty($menusItemData['id'])){
            $menuItem = MenusModel::find($menusItemData['id']);
            $menuItem->save($menusItemData);
        }else{
            MenusModel::create($menusItemData);
        }
        return true;
    }

    /**
     * 获取所有菜单（无限级树状结构），仅允许超级管理员
     * @return array
     * @throws Exception
     */
    public static function getAllMenus(): array
    {
        $menus = MenusModel::order('sort', 'asc')
            ->select()
            ->toArray();
        return ['tree'=>Utils::buildTree($menus,0)];
    }
}